import axios from "axios"
import token from "./token"

// const VUE_APP_URL = process.env.VUE_APP_URL
const VUE_APP_URL_VERSION = process.env.VUE_APP_URL_VERSION
const prefixURL = VUE_APP_URL_VERSION ? "/" + VUE_APP_URL_VERSION : ""

// 创建 axios 实例
let http = axios.create({
  baseUrl:
    process.env.NODE_ENV === "development" ? "/" : process.env.VUE_APP_URL,
  timeout: 10000, // 请求超时时间
  crossDomain: true, //设置cross跨域
  withCredentials: true, //设置cross跨域 并设置访问权限 允许跨域携带cookie信息
})

// http request拦截器 添加一个请求拦截器
http.interceptors.request.use(
  (config) => {
    // Do something before request is sent
    //config.withCredentials = true // 允许携带token ,这个是解决跨域产生的相关问题
    config.timeout = 6000
    //config.headers["Content-Type"] = "application/x-www-form-urlencoded"
    config.headers["Content-Type"] = "application/json"
    config.headers["token"] = token.getRefreshToken() // 将token放到请求头发送给服务器
    return config
  },
  (error) => {
    // Do something with request error
    return Promise.reject(error)
  }
)

export default async () => {
  let url = prefixURL + "/token/refresh?timestamp=" + new Date().getTime()

  try {
    const respone = await http.get(url)
    if (respone.status == 200) {
      token.set(respone.data.data.access_token, respone.data.data.refresh_token)
    }
    return respone.status
  } catch (error) {
    console.log(error)
    return 401
  }
}
